package com.zork.cmdb.webapi.datasource.configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author chenjh
 * @date 2018/6/25
 * @description
 */

@Configuration
@MapperScan(basePackages = "com.zork.cmdb.webapi.mapper.cmdb", sqlSessionTemplateRef  = "cmdbSqlSessionTemplate")
public class CmdbDataSourceConfiguration extends BaseDataSourceConfiguration {

    @Override
    @Bean(name = "cmdbDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.cmdb")
    @Primary
    public DataSource createDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Override
    @Bean(name = "cmdbSqlSessionFactory")
    @Primary
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("cmdbDataSource") DataSource dataSource) throws Exception {
        return super.getSqlSessionFactory(dataSource);
    }

    @Override
    @Bean(name = "cmdbTransactionManager")
    @Primary
    public DataSourceTransactionManager getTransactionManager(@Qualifier("cmdbDataSource") DataSource dataSource) {
        return super.getTransactionManager(dataSource);
    }

    @Override
    @Bean(name = "cmdbSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate getSqlSessionTemplate(@Qualifier("cmdbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return super.getSqlSessionTemplate(sqlSessionFactory);
    }

}